package com.heima.behavior.service.impl;

import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApBehaviorEntryService implements IApBehaviorEntryService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * APP 端-文章详情页-查询登录用户的行为实体
     * @param userId
     * @param equipmentId
     * @return
     */
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //查询行为实体，优先使用登录用户 id，次要考虑登录设备 id
        if(userId != null){
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(
                    Query.query(Criteria.where("ref_id").is(userId).and("type").is(ApBehaviorEntry.Type.USER.getCode())),
                    ApBehaviorEntry.class);
            if(apBehaviorEntry == null){
                apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                apBehaviorEntry.setRefId(userId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
            }
            return apBehaviorEntry;
        }
        if(equipmentId != null){
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(Query.query(
                    Criteria.where("ref_id").is(equipmentId).and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode())),
                    ApBehaviorEntry.class);
            if(apBehaviorEntry == null){
                apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                apBehaviorEntry.setRefId(equipmentId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
            }
            return apBehaviorEntry;
        }
        return null;
    }
}
